/* eslint-disable react-native/no-inline-styles */
import React, {Component} from 'react';
import {
  View,
  Text,
  StyleSheet,
  BackHandler,
  ToastAndroid,
  Platform,
  Vibration,
} from 'react-native';
import WebView from 'react-native-webview';
import KeyboardSpacer from 'react-native-keyboard-spacer';
import {Native} from '../../lib/core.js';
import CookieManager from 'react-native-cookies';
import SplashScreen from 'react-native-splash-screen';
import Orientation from 'react-native-orientation';
import JPushModule from 'jpush-react-native';
import ImagePicker from 'react-native-image-crop-picker';
import {AudioRecorder, AudioUtils} from 'react-native-audio';
import {AnimatedCircularProgress} from 'react-native-circular-progress';
import {check, PERMISSIONS, RESULTS, request} from 'react-native-permissions';
import Sound from 'react-native-sound';

export default class Home extends Component {
  constructor(props) {
    super(props);
    this.state = {
      source: null,
      currentVideo: null,
      load: false,
      num: 1,
      num2: 1,
      fill: 0,
    };
  }
  _onMessage = (e) => {
    const msg = e.nativeEvent.data;
    this.native.message(msg);
  };
  _onLoadEnd = () => {
    if (this.state.source !== null) {
      SplashScreen.hide();
    }
  };
  _renderError = (domain, code, desc) => {
    return (
      <View style={styles.error}>
        <Text>{desc}</Text>
      </View>
    );
  };
  _openCamera = (param, callback) => {
    //打开相机
    const {cropping} = param;
    ImagePicker.openCamera({
      compressImageQuality: 0.5,
      cropping: cropping,
    }).then((image) => {
      this.setState({load: true}, () => {
        this.circularProgress.animate(80, 3000);
        this._upload(param, image, (res) => {
          callback(res);
          this.circularProgress.animate(100, 200);
          this.setState({load: false});
        });
      });
    });
  };
  _openFile = (param, callback) => {
    //相册单选
    const {cropping} = param;
    ImagePicker.openPicker({
      mediaType: 'photo',
      cropping: cropping,
    }).then((image) => {
      this.setState({load: true}, () => {
        this.circularProgress.animate(80, 3000);
        this._upload(param, image, (res) => {
          callback(res);
          this.circularProgress.animate(100, 200);
          this.setState({load: false});
        });
      });
    });
  };
  _openFileMultiple = (param, callback) => {
    //相册多选
    ImagePicker.openPicker({
      mediaType: 'photo',
      multiple: true,
    }).then((image) => {
      this.setState({load: true, num: image.length}, () => {
        this.circularProgress.animate(10, 3000);
        image.forEach((e, i) => {
          this.setState({num2: i + 1});
          // console.log(i + 1);
          this._upload(param, e, (res) => {
            callback(res);
            this.circularProgress.animate((100 / image.length) * i, 10);
            if (i + 1 === image.length) {
              this.circularProgress.animate(100, 10, () => {
                this.setState({load: false, num2: 1});
              });
            }
          });
        });
      });
    });
  };
  _phoneVideo = (param, callback) => {
    //手机摄像机
    ImagePicker.openCamera({
      mediaType: 'video',
    }).then((image) => {
      this._upload(param, image, (res) => {
        callback(res);
      });
    });
  };
  _takeVideo = (param, callback) => {
    //摄像机
    console.log(param.uploadServer);
    this.props.navigation.navigate('TakeVideo', {
      callback: (data) => {
        console.log(data.uri);
        this.props.navigation.navigate('Player', {
          url: data.uri,
          type: 'upload',
          api: param.uploadServer,
          fun: (res) => {
            callback(res);
          },
        });
      },
    });
  };
  _openVideoFile = (param, callback) => {
    //打开手机视频文件
    ImagePicker.openPicker({
      mediaType: 'video',
    }).then((image) => {
      this.setState({load: true}, () => {
        this.circularProgress.animate(80, 3000);
        this._upload(
          param,
          image,
          (res) => {
            callback(res);
            this.circularProgress.animate(100, 200);
            this.setState({load: false});
          },
          '.mp4',
        );
      });
    });
  };
  _openScanner() {
    //扫描二维码
    let param = {
      ios: PERMISSIONS.IOS.CAMERA,
      android: PERMISSIONS.ANDROID.CAMERA,
    };
    this._permissions(
      param,
      this.props.navigation.navigate('Scanner', {
        callback: (data) => {
          //回调
          this.native.post({
            name: 'onBarCodeRead',
            payload: data,
          });
        },
      }),
    );
  }
  _playVideo = (video) => {
    //直播
    this.setState({currentVideo: video});
    this.props.navigation.navigate('PlayView', {
      url: this.state.currentVideo.url,
      name: this.state.currentVideo.name,
      history: this.state.currentVideo.history,
    });
  };

  _imageView(data) {
    //查看图片
    this.props.navigation.navigate('ImgView', {
      arr: data.list,
      index: data.i,
    });
  }
  _openShortVideo(url) {
    //查看短视频
    this.props.navigation.navigate('Player', {
      url: url,
      type: 'play',
    });
  }
  _pdfView = (url) => {
    //查看pdf
    this.props.navigation.navigate('PDF', {
      uri: url,
      cache: true,
    });
  };

  async _openAudio() {
    //开始录音
    console.log(AudioUtils);
    let audioPath = AudioUtils.DocumentDirectoryPath + '/test.aac';
    AudioRecorder.prepareRecordingAtPath(audioPath, {
      SampleRate: 22050,
      Channels: 1,
      AudioQuality: 'Low', //录音质量
      AudioEncoding: 'aac', //录音格式
      AudioEncodingBitRate: 32000, //比特率
    });
    try {
      const filePath = await AudioRecorder.startRecording();
      console.log(filePath);
    } catch (error) {
      console.error(error);
    }
  }
  async _stopAudio(param, callback) {
    // 停止录音
    try {
      const filePath = await AudioRecorder.stopRecording();
      let file = {path: 'file://' + filePath, mime: 'audio/aac'};
      this._upload(
        param,
        file,
        (data) => {
          callback(data);
        },
        '.acc',
      );
      return filePath;
    } catch (error) {
      console.error(error);
    }
  }
  _playAudio(url) {
    //播放录音
    console.log(url);
    var whoosh = new Sound(url, Sound.MAIN_BUNDLE, (error) => {
      if (error) {
        console.log('加载音频失败', error);
        ToastAndroid.show('加载音频失败', ToastAndroid.SHORT);
        return;
      }
      // 成功加载
      console.log(
        'duration in seconds: ' +
          whoosh.getDuration() +
          'number of channels: ' +
          whoosh.getNumberOfChannels(),
      );

      //使用onEnd回调
      whoosh.play((success) => {
        if (success) {
          console.log('成功完成播放');
        } else {
          console.log('由于音频解码错误导致播放失败');
          ToastAndroid.show('由于音频解码错误导致播放失败', ToastAndroid.SHORT);
        }
      });
    });
  }
  _Shock(param) {
    //手机震动
    Vibration.vibrate(param.pattern, false);
  }
  _permissions(param, fn) {
    //权限请求
    check(Platform.OS === 'ios' ? param.ios : param.android).then((result) => {
      switch (result) {
        case RESULTS.UNAVAILABLE:
          ToastAndroid.show('此设备不支持该功能', ToastAndroid.SHORT);
          break;
        case RESULTS.DENIED:
          console.log('开始请求权限');
          request(Platform.OS === 'ios' ? param.ios : param.android).then(
            (result) => {
              if (result) {
                fn();
              }
            },
          );
          break;
        case RESULTS.GRANTED:
          console.log('已通过');
          fn();
          break;
        case RESULTS.BLOCKED:
          console.log('The permission is denied and not requestable anymore');
          ToastAndroid.show('权限被拒绝,请前往授予权限', ToastAndroid.SHORT);

          break;
      }
    });
  }
  _upload = (param, file, callback, type = null) => {
    // 把文件上传到服务器，具体需要根据接口更改,此处为天池53上传接口
    var uploadUrl = param.uploadServer;
    let formData = new FormData();
    let files = {uri: file.path, type: file.mime, name: '11'};
    formData.append('file', files);
    if (type != null) {
      formData.append('type', type);
    }

    return new Promise((resolve) => {
      fetch(uploadUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'multipart/form-data;charset=utf-8',
        },
        body: formData,
      })
        .then((response) => response.json())
        .then((responseData) => {
          console.log(responseData);
          if (responseData.code === 0) {
            callback(responseData.result);
          }
          // this.circularProgress.animate(100, 200)
          // this.setState({res:responseData})
        })
        .catch((err) => {
          console.log('err', err);
        });
    });
  };
  initNative() {
    //web需要调用的方法
    this.native = new Native(this.webview);
    this.native.define('SetAlias', JPushModule.setAlias);
    // this.native.define('SetTags', JPushModule.SetTags);
    this.native.define('ClearCookie', this.destroyCookies.bind(this));
    this.native.define('openScanner', this._openScanner.bind(this));
    this.native.define('openCamera', this._openCamera.bind(this));
    this.native.define('openFile', this._openFile.bind(this));
    this.native.define('openFileMultiple', this._openFileMultiple.bind(this));
    this.native.define('takeVideo', this._takeVideo.bind(this));
    this.native.define('openAudio', this._openAudio.bind(this));
    this.native.define('stopAudio', this._stopAudio.bind(this));
    this.native.define('playAudio', this._playAudio.bind(this));
    this.native.define('openShortVideo', this._openShortVideo.bind(this));
    this.native.define('openVideoFile', this._openVideoFile.bind(this));
    this.native.define('pdfView', this._pdfView.bind(this));
    this.native.define('phoneVideo', this._phoneVideo.bind(this));
    this.native.define('PlayVideo', this._playVideo.bind(this));
    this.native.define('imageView', this._imageView.bind(this));
    this.native.define('Shock', this._Shock.bind(this));
    this.native.define('lockToLandscape', this._lockToLandscape.bind(this));
    this.native.define('lockToPortrait', this._lockToPortrait.bind(this));
  }
  _lockToLandscape = () => {
    Orientation.lockToLandscape();
  };

  _lockToPortrait = () => {
    Orientation.lockToPortrait();
  };

  _openNotificationListener = (payload) =>
    this.native.post({name: 'notify', payload: payload});
  initPush() {
    if (Platform.OS === 'android') {
      JPushModule.init();
      JPushModule.addNotificationListener(this._openNotificationListener);
      // JPushModule.notifyJSDidLoad(() => {});
    } else if (Platform.OS === 'ios') {
      JPushModule.loadJS();
      JPushModule.setBadge(0, () => {});
    }
    JPushModule.clearAllNotifications();
  }

  initWebView() {
    this.setState({
      // source: { uri: 'http://192.168.0.210:8080/#/' },
      source: {uri: 'http://192.168.3.94:8080/#/'},

      // source: {uri: 'http://192.168.0.42:8080/#/extras/topo/1571883716800'},
    });
  }

  componentDidMount() {
    BackHandler.addEventListener(
      'hardwareBackPress',
      this.onBackButtonPressAndroid,
    );
    this.initPush();
    this.initNative();
    this.initWebView();
  }
  componentWillUnmount() {
    this.destroyCookies();
    this.destroyPush();
    BackHandler.removeEventListener(
      'hardwareBackPress',
      this.onBackButtonPressAndroid,
    );
  }
  destroyCookies() {
    CookieManager.clearAll();
  }
  onBackButtonPressAndroid = () => {
    if (this.lastBackPressed && this.lastBackPressed + 2000 >= Date.now()) {
      return BackHandler.exitApp();
    } else {
      this.native.post({
        name: 'back',
        payload: {},
        callback: (flag) => {
          console.log(flag);
          if (!flag) {
            console.log(flag);
            this.lastBackPressed = Date.now();
            ToastAndroid.show('再按一次退出应用', ToastAndroid.SHORT);
          }
        },
      });
      return true;
    }
  };
  destroyPush() {
    JPushModule.removeListener(this._openNotificationListener);
  }
  loading() {
    if (this.state.load) {
      return (
        <View style={styles.loading}>
          <AnimatedCircularProgress
            ref={(ref) => (this.circularProgress = ref)}
            size={80}
            width={5}
            fill={this.state.fill}
            tintColor="#00e0ff"
            onAnimationComplete={() => {
              console.log('onAnimationComplete');
            }}
            backgroundColor="#3d5875">
            {(fill) => (
              <Text style={{color: '#fff'}}>
                {this.state.num2 + '/' + this.state.num}
              </Text>
            )}
          </AnimatedCircularProgress>
        </View>
      );
    } else {
      return null;
    }
  }
  render() {
    return (
      <View style={styles.container}>
        <WebView
          ref={(webview) => (this.webview = webview)}
          source={this.state.source}
          onMessage={this._onMessage}
          onLoadEnd={this._onLoadEnd}
          onError={(syntheticEvent) => {
            const {nativeEvent} = syntheticEvent;
            this._renderError(
              nativeEvent.domain,
              nativeEvent.code,
              nativeEvent.description,
            );
          }}
          javaScriptEnabled={true}
          domStorageEnabled={true}
          useWebKit={true}
          bounces={false}
          allowFileAccess={true}
          allowUniversalAccessFromFileURLs={true}
        />
        <KeyboardSpacer />
        {this.loading()}
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    position: 'relative',
    flex: 1,
    backgroundColor: '#000',
  },
  webview: {
    flex: 1,
  },
  error: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  loading: {
    width: 100,
    height: 100,
    padding: 10,
    borderRadius: 8,
    backgroundColor: 'rgba(0,0,0,0.3)',
    position: 'absolute',
    top: '50%',
    left: '38%',
  },
});
